"""
邮件发送功能
"""
from flask import current_app
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header


def send_email(subject, recipients, html_content, sender_name=None):
    """
    发送邮件
    
    Args:
        subject: 邮件主题
        recipients: 收件人列表
        html_content: HTML格式的邮件内容
        sender_name: 发件人名称，可选
    
    Returns:
        bool: 是否发送成功
    """
    try:
        # 获取邮件配置
        mail_server = current_app.config.get('MAIL_SERVER', 'smtp.example.com')
        mail_port = current_app.config.get('MAIL_PORT', 587)
        mail_use_tls = current_app.config.get('MAIL_USE_TLS', True)
        mail_use_ssl = current_app.config.get('MAIL_USE_SSL', False)
        mail_username = current_app.config.get('MAIL_USERNAME', '')
        mail_password = current_app.config.get('MAIL_PASSWORD', '')
        mail_default_sender = current_app.config.get('MAIL_DEFAULT_SENDER', 'noreply@example.com')
        
        # 创建邮件对象
        msg = MIMEMultipart('alternative')
        msg['Subject'] = Header(subject, 'utf-8')
        msg['From'] = f"{sender_name or '系统通知'} <{mail_default_sender}>"
        msg['To'] = ', '.join(recipients)
        
        # 添加HTML内容
        html_part = MIMEText(html_content, 'html', 'utf-8')
        msg.attach(html_part)
        
        # 连接SMTP服务器并发送邮件
        if mail_use_ssl:
            server = smtplib.SMTP_SSL(mail_server, mail_port)
        else:
            server = smtplib.SMTP(mail_server, mail_port)
            if mail_use_tls:
                server.starttls()
        
        if mail_username and mail_password:
            server.login(mail_username, mail_password)
        
        server.send_message(msg)
        server.quit()
        
        current_app.logger.info(f"邮件发送成功: {subject} -> {recipients}")
        return True
        
    except Exception as e:
        current_app.logger.error(f"邮件发送失败: {str(e)}")
        return False